//
//  LocalFileManager.swift
//  Crypto
//
//  Created by DaleGuo on 2023/9/22.
//

import Foundation
import SwiftUI

/// 稍微通用一点的
/// 唯一不同的地方在于getImagePath的后缀
class LocalFileManager {
    static let instance = LocalFileManager()

    private init() {}
        
    private func createFolderNeeded(folderName: String) {
        guard let url = getFolderPath(folderName: folderName) else {
            return
        }
            
        if !FileManager.default.fileExists(atPath: url.path) {
            do {
                try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
                print("______create folder______")
                          
            } catch {
                print("Create Folder ERRER: \(error)")
            }
        }
    }
        
    private func getFolderPath(folderName: String) -> URL? {
        return FileManager
            .default
            .urls(for: .cachesDirectory, in: .userDomainMask)
            .first?
            .appendingPathComponent(folderName)
    }
    
    func getImagePath(key: String, foolderName: String) -> URL? {
        guard let folder = getFolderPath(folderName: foolderName) else {
            return nil
        }
            
        return folder.appendingPathComponent(key + ".png")
    }
        
    func save(image: UIImage, key: String, folderName: String) {
        createFolderNeeded(folderName: folderName)
        
        guard
            let data = image.pngData(),
            let url = getImagePath(key: key, foolderName: folderName) // 生成image路径
        else {
            return
        }
            
        do {
//            print("Save data in file : url---=  \(url)")
            try data.write(to: url)
        } catch {
            print("Save Data in File ERROR: \(error)")
        }
    }
        
    func get(key: String, folderName: String) -> UIImage? {
        guard
            let url = getImagePath(key: key, foolderName: folderName),
            FileManager.default.fileExists(atPath: url.path)
        else {
            return nil
        }
            
        return UIImage(contentsOfFile: url.path)
    }
}
